package crawler;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;

public class Robot {
	private String host;// this is the id of the robot
	private MessageBox msgBox;

	public String getHost() {
		return host;
	}

	private ArrayList<String> disallowedPaths = new ArrayList<String>();
	private ArrayList<String> allowedPaths = new ArrayList<String>();

	public Robot(String robottxt, String host) {
		this.host = host;
		if (robottxt != null) {
			robottxt = robottxt.toLowerCase();
			String[] strArr = robottxt.split("\n");
			// TODO: check user agent
			for (String string : strArr) {
				if (!extractURL(string, "disallow:", disallowedPaths))
					extractURL(string, "allow:", allowedPaths);
			}
		}
	}

	private boolean extractURL(String string, String pattern,
			ArrayList<String> collection) {
		int idx = string.indexOf(pattern);
		if (idx != -1) {
			collection.add(string.substring(idx + pattern.length()));
			return true;
		}
		return false;
	}

	public boolean isAllowed(URL url) {
		String path = url.getPath();
		/*if(disallowedPaths.size()>0)
		{
			System.out.println("!!!!!!!!!!!!");
		}*/
		int allowLCP = getLongestCommonPrefix(path, allowedPaths);
		int disallowLCP = getLongestCommonPrefix(path, disallowedPaths);

		if(allowLCP==-1&&disallowLCP==-1) return true;
		//System.out.println("In Robot-checker: allowLCP="+allowLCP+", disallowLCP="+disallowLCP);
		return allowLCP > disallowLCP;
	}

	private int getLongestCommonPrefix(String path, ArrayList<String> collection) {
		int longestCommonPrefix = -1;
		for (String p : collection) {
			longestCommonPrefix = greatestCommonPrefix(path, p);
		}
		return longestCommonPrefix;
	}

	private int greatestCommonPrefix(String a, String b) {
		int minLength = Math.min(a.length(), b.length());
		for (int i = 0; i < minLength; i++) {
			if (a.charAt(i) != b.charAt(i)) {
				return i;
			}
		}
		return minLength;
	}

	private boolean isHTML(String url) {
		boolean isHTML = false;
		if (url.endsWith(".html"))
			isHTML = true;
		return isHTML;
	}
}
